﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.PatientMobileDevice;
using B.S.DataBase.MyProject.Domain.wdx;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.Sign;
using SqlSugar;

namespace MedicalPCTerminal.Write.API.Appcation.CommandHandlers.Sign
{
    public class AddNCDSignCommandHandler : IRequestHandler<AddNCDSignCommand, APIResult<object>>
    {
        private readonly SqlSugarContext sqlSugar;
        private readonly IMapper mapper;

        public AddNCDSignCommandHandler(SqlSugarContext sqlSugar, IMapper mapper)
        {
            this.sqlSugar = sqlSugar;
            this.mapper = mapper;
        }

        public Task<APIResult<object>> Handle(AddNCDSignCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            // 使用SqlSugar的事务
            try
            {
                sqlSugar.db.Ado.BeginTran(); // 开启事务

                // 1. 添加NCDSign记录
                var model = mapper.Map<NCDSign>(request);
                var r = sqlSugar.db.Insertable(model).ExecuteCommand();
                if (r <= 0)
                {
                    throw new Exception("添加NCDSign记录失败");
                }

                // 2. 添加Me记录
                var residentFiles = sqlSugar.db.Queryable<ResidentFiles>().InSingle(request.Patient_Id);
                if (residentFiles != null)
                {
                    Me me = new Me
                    {
                        UserName = residentFiles.ResidentFiles_Name,
                        Age = residentFiles.Age,
                        Phone = residentFiles.Phone,
                        Sex = residentFiles.Sex.Value ? "男" : "女",
                        Password = "123"
                    };

                    var meAdd = sqlSugar.db.Insertable(me).ExecuteCommand();
                    if (meAdd <= 0)
                    {
                        throw new Exception("添加Me记录失败");
                    }
                }

                sqlSugar.db.Ado.CommitTran(); // 提交事务

                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
                result.data = model;
            }
            catch (Exception ex)
            {
                sqlSugar.db.Ado.RollbackTran(); // 回滚事务
                result.Code = APIEnum.添加失败;
                result.Msg = $"添加失败: {ex.Message}";
                result.data = null;
            }

            return Task.FromResult(result);
        }
    }
}